<?php

namespace app\admin\controller;

use app\BaseController;
use app\common\result\Result;
use app\model\Permission;
use app\model\Role as ModelRole;
use think\facade\Request;

class Role extends BaseController
{

    protected $middleware = [
        'auth',
        'checkPermission'

    ];

    public function index()
    {

        $pageNum = Request::param('pageNum');
        $pageSize = Request::param('pageSize');

        $roleList = ModelRole::with('permissions')->page($pageNum, $pageSize)->select();

        return Result::Success($roleList);
    }

    public function add()
    {
        $name = Request::post('name');

        $hasRole = ModelRole::where('name', $name)->findOrEmpty();
        if ($hasRole->isEmpty()) {

            $role = new ModelRole();
            $role->name = $name;

            $role->save();

            return Result::Success($role);
        } else {
            return Result::Error(500, '同名角色已存在');
        }
    }

    /**
     * 绑定权限关系
     */
    public function bindPermission()
    {
        $permissionId = Request::post('permissionId');
        $roleId = Request::post('roleId');

        // $permission = Permission::find($permissionId);
        $role = ModelRole::find($roleId);

        $role->permissions()->attach($permissionId);

        return Result::Success([]);
    }

    /**
     * 解绑权限关系
     */
    public function unBindPermission()
    {
        $permissionId = Request::post('permissionId');
        $roleId = Request::post('roleId');

        $role = ModelRole::find($roleId);
        $result = $role->permissions()->detach([$permissionId]);

        if ($result > 0) {
            return Result::Success([]);
        } else {
            return Result::Error(500, '不存在绑定关系');
        }
    }
}
